function HierarkiaWebGL(doc, ui)
{
    var canvas = doc.createElement("canvas");
    canvas.width = "800";
    canvas.height = "600";
    this.canvas = canvas;

    this.gl = this.canvas.getContext("experimental-webgl");
    if(!this.gl) return;
    
    var glcanvas = new WebGLCanvas(this.gl);
    var cameracontroller = new CameraController(Math.PI/4, Math.PI/3);
  
    function repaint()
    {
        var width = canvas.clientWidth;
        var height = canvas.clientHeight;

		var latlon = cameracontroller.readreset(width, height);
		var cameradistance = 15.0;

        glcanvas.draw(width, height, latlon[1], latlon[0], cameradistance);
    }

    this.canvas.onmousemove = function(evt)
    {
        var boardxy = glcanvas.unproject(evt.clientX, evt.clientY);
        if(boardxy) glcanvas.setMouseOver(boardxy);
        var cameramove = cameracontroller.onmousemove(evt);
        if(cameramove || boardxy)
        {
            repaint();
        }
    }

    this.canvas.onclick = function(evt)
    {
        var boardxy = glcanvas.unproject(evt.clientX, evt.clientY);
        if(boardxy) ui.cellClicked(boardxy[0], boardxy[1]);
    }

    
    this.updateCurrentGame = function(player, game, fsm)
    {
        glcanvas.update(player, game, fsm);
        repaint();
    }

    this.updateGamesList = function(player, currentGameId, games) {}
}

function initHierarkiaWebGL(doc, ui, ondone, onerror)
{
    function init()
    {
        try
        {
            var view = new HierarkiaWebGL(doc, ui);
            if(!view.gl) onerror("Cannot initialize WebGL: null GL!");
            ondone(view);
        } catch(e)
        {
            onerror("Cannot initialize WebGL view: " + e);
        }
    }
    
    setTimeout(init, 0);
}


